package com.atguigu.aspect;

import com.atguigu.annotation.CustomerLogAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class CustomerLogAspect {

    @Around("@annotation(com.atguigu.annotation.CustomerLogAnnotation)")
    public Object logAroud(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = null;
        //通过反射获取方法名
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();

        //检查方法上是否有自定义注解
        CustomerLogAnnotation customerLogAnnotation = method.getAnnotation(CustomerLogAnnotation.class);
        if (customerLogAnnotation != null && customerLogAnnotation.enable()) {
            long startTime = System.currentTimeMillis();
            System.out.println("方法执行前");
            result = proceedingJoinPoint.proceed();
            System.out.println("方法执行后" + customerLogAnnotation.value());
            long endTime = System.currentTimeMillis();
            System.out.println("耗时时间costTime = " + (endTime - startTime) + "毫秒");
            return result;
        } else {
            return proceedingJoinPoint.proceed();

        }
    }
}
